import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { Form, Input, Modal } from 'antd';
import { addArticle } from '../../api/modules/article';
import Markdown from '../../components/Markdown';
import store from '../../store';
const ModalCom = (props: any, ref: any) => {
    const [ isModalOpen, setIsModalOpen ] = useState(false);
    const [ form ] = Form.useForm();
    const mdRef = useRef<any>(null);
    const { getList } = props;
    useImperativeHandle(ref, () => {
        return {
            showModal: showModal,
        };
    });
  type FieldType = {
    username?: string;
    password?: string;
  };
  const showModal = (record: any) => {
      if (record) {
          form.setFieldsValue(record);
          console.log(record, 'record');
          console.log(mdRef.current!.mdContent, ' mdRef.current!.mdContent ');
      mdRef.current!.mdContent = record.content;
      } else {
          form.resetFields();
      }
      setIsModalOpen(true);
  };
  const textContent = `console.log(1)`;
  useEffect(() => {
      if (isModalOpen) {
      }
  }, [ isModalOpen ]);
  // <MarkDownPreView content={text}></MarkDownPreView>
  const handleOk = () => {
      form
          .validateFields()
          .then(async (valid) => {
              const content = mdRef.current!.mdContent;
              const user = store.getState().user.userinfo.username;
              const id = form.getFieldValue('id');
              const params = { ...valid, content, user, id };
              const result = await addArticle(params);
              setIsModalOpen(false);
              getList();
          })
          .catch((err) => {
              return false;
          });
  };

  const handleCancel = () => {
      setIsModalOpen(false);
  };

  return (
      <>
          <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={900}>
              <Form form={form} name="basic" labelCol={{ span: 1 }} wrapperCol={{ span: 16 }} style={{ maxWidth: 1000, maxHeight: 600, overflowY: 'auto' }} initialValues={{ remember: true }} autoComplete="off">
                  <Form.Item<FieldType> label="标题" name="name">
                      <Input />
                  </Form.Item>
                  <Form.Item<FieldType> label="内容" name="content" wrapperCol={{ span: 24 }}>
                      <Markdown ref={mdRef} />
                  </Form.Item>
              </Form>
          </Modal>
      </>
  );
};

export default forwardRef(ModalCom);
